﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;

namespace Yule8xModel
{
    public class WithDrawModels
    {
        /// <summary>
        /// 提现申请
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="mobile"></param>
        /// <param name="amount"></param>
        /// <param name="bankcard_id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool WithDrawSubmit(int user_id,string mobile, decimal amount, int bankcard_id,out string msg)
        {
            if (string.IsNullOrWhiteSpace(mobile) || amount < 1 || bankcard_id < 1)
            {
                msg = "表单数据有误";
                return false;
            }
            // 判断金额
            decimal blance = UserModels.GetUserAccountBlance(user_id);
            if (amount > blance)
            {
                msg = "[提现申请] 提现金额不能超过账户余额";
                LogUtil.Instance.WriteInfo(msg);
                return false;
            }
            // 获取银行卡信息
            string sqlstmt = string.Format("select bank_account, bank_holder, bank_name from t_bankcard where id={0}", bankcard_id);
            DataTable dtBankCardItem = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sqlstmt);
            if (dtBankCardItem.Rows.Count < 1)
            {
                msg = "[提现申请] 银行卡不存在";
                LogUtil.Instance.WriteInfo(msg);
                return false;
            }
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("pay_channel", "bank");
            data.Add("account", dtBankCardItem.Rows[0]["bank_account"].ToString());
            data.Add("holder", dtBankCardItem.Rows[0]["bank_holder"].ToString());
            data.Add("bank_name", dtBankCardItem.Rows[0]["bank_name"].ToString());
            data.Add("amount", amount.ToString());
            data.Add("user_id", user_id.ToString());
            data.Add("status", "0");
            sqlstmt = DbFactory.GetInsertStatement("t_finance_withdraw", data);
            LogUtil.Instance.WriteInfo("[提现申请] " + sqlstmt);
            int count = DbFactory.Instance.ExecuteNonQuery(sqlstmt);
            if (count < 1)
            {
                msg = "[提现申请] 失败: " + sqlstmt;
                LogUtil.Instance.WriteInfo(msg);
                return false;
            }
            else
            {
                // 更新用户表可用余额和不可用余额
                sqlstmt = string.Format("update t_user_finance_account set blance=blance-{0}, frozen_blance=frozen_blance+{0} where user_id={1}", amount, user_id);
                DbFactory.Instance.ExecuteNonQuery(sqlstmt);
                msg = "[ 提现申请] 成功: " + sqlstmt;
                LogUtil.Instance.WriteInfo(msg);
                return true;
            }
        }
    }
}
